const { query } = require('../config/database');
const Friend = require('./Friend');

class Post {
  /**
   * 创建动态
   * @param {string} userId - 用户ID
   * @param {string} content - 动态内容
   * @returns {Object} 创建的动态信息
   */
  static async create(userId, content) {
    try {
      // 参数验证
      if (!content || content.trim().length === 0) {
        throw new Error('动态内容不能为空');
      }
      
      if (content.length > 1000) {
        throw new Error('动态内容不能超过1000个字符');
      }

      const insertSql = `
        INSERT INTO posts (user_id, content) 
        VALUES (?, ?)
      `;
      
      const result = await query(insertSql, [userId, content.trim()]);
      
      // 获取刚创建的动态
      return await Post.getById(result.insertId, userId);
    } catch (error) {
      console.error('创建动态失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID获取动态详情
   * @param {number} postId - 动态ID
   * @param {string} currentUserId - 当前用户ID
   * @returns {Object|null} 动态信息
   */
  static async getById(postId, currentUserId) {
    try {
      const sql = `
        SELECT 
          p.id,
          p.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          p.content,
          p.created_at as createdAt,
          p.updated_at as updatedAt,
          -- 统计点赞数
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id) as likeCount,
          -- 统计评论数
          (SELECT COUNT(*) FROM post_comments WHERE post_id = p.id AND status = 1) as commentCount,
          -- 当前用户是否已点赞
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id AND user_id = ?) > 0 as isLiked
        FROM posts p
        LEFT JOIN users u ON p.user_id = u.user_id
        WHERE p.id = ? AND p.status = 1
      `;
      
      const posts = await query(sql, [currentUserId, postId]);
      return posts.length > 0 ? posts[0] : null;
    } catch (error) {
      console.error('获取动态详情失败:', error);
      throw error;
    }
  }

  /**
   * 获取好友动态列表
   * @param {string} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 动态列表和分页信息
   */
  static async getFriendsPosts(userId, page = 1, limit = 10) {
    try {
      // 确保参数为整数类型
      page = parseInt(page);
      limit = parseInt(limit);
      
      const offset = (page - 1) * limit;
      
      // 获取好友动态列表（包括自己的动态）
      const sql = `
        SELECT 
          p.id,
          p.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          p.content,
          p.created_at as createdAt,
          -- 统计点赞数
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id) as likeCount,
          -- 统计评论数
          (SELECT COUNT(*) FROM post_comments WHERE post_id = p.id AND status = 1) as commentCount,
          -- 当前用户是否已点赞
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id AND user_id = ?) > 0 as isLiked
        FROM posts p
        LEFT JOIN users u ON p.user_id = u.user_id
        WHERE p.status = 1 
          AND (
            p.user_id = ? 
            OR p.user_id IN (
              SELECT friend_id FROM friendships 
              WHERE user_id = ? AND status = 1
            )
          )
        ORDER BY p.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const posts = await query(sql, [userId, userId, userId]);
      
      // 为每个动态获取评论数据
      for (let post of posts) {
        const commentSql = `
          SELECT 
            c.id,
            c.user_id as userId,
            u.nick_name as userNickName,
            c.content,
            c.created_at as createdAt
          FROM post_comments c
          LEFT JOIN users u ON c.user_id = u.user_id
          WHERE c.post_id = ? AND c.status = 1
          ORDER BY c.created_at ASC
        `;
        
        post.comments = await query(commentSql, [post.id]);
      }
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM posts p
        WHERE p.status = 1 
          AND (
            p.user_id = ? 
            OR p.user_id IN (
              SELECT friend_id FROM friendships 
              WHERE user_id = ? AND status = 1
            )
          )
      `;
      
      const countResult = await query(countSql, [userId, userId]);
      const total = countResult[0].total;
      
      return {
        posts,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取动态列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户动态列表
   * @param {string} targetUserId - 目标用户ID
   * @param {string} currentUserId - 当前用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 动态列表和分页信息
   */
  static async getUserPosts(targetUserId, currentUserId, page = 1, limit = 10) {
    try {
      // 验证权限：只能查看自己或好友的动态
      if (targetUserId !== currentUserId) {
        const isFriend = await Friend.isFriend(currentUserId, targetUserId);
        if (!isFriend) {
          throw new Error('只能查看好友的动态');
        }
      }
      
      // 确保参数为整数类型
      page = parseInt(page);
      limit = parseInt(limit);
      
      const offset = (page - 1) * limit;
      
      const sql = `
        SELECT 
          p.id,
          p.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          p.content,
          p.created_at as createdAt,
          -- 统计点赞数
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id) as likeCount,
          -- 统计评论数
          (SELECT COUNT(*) FROM post_comments WHERE post_id = p.id AND status = 1) as commentCount,
          -- 当前用户是否已点赞
          (SELECT COUNT(*) FROM post_likes WHERE post_id = p.id AND user_id = ?) > 0 as isLiked
        FROM posts p
        LEFT JOIN users u ON p.user_id = u.user_id
        WHERE p.user_id = ? AND p.status = 1
        ORDER BY p.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const posts = await query(sql, [currentUserId, targetUserId]);
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM posts 
        WHERE user_id = ? AND status = 1
      `;
      
      const countResult = await query(countSql, [targetUserId]);
      const total = countResult[0].total;
      
      return {
        posts,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取用户动态列表失败:', error);
      throw error;
    }
  }

  /**
   * 删除动态
   * @param {number} postId - 动态ID
   * @param {string} userId - 用户ID
   * @returns {boolean} 删除结果
   */
  static async delete(postId, userId) {
    try {
      // 验证动态是否存在且属于当前用户
      const checkSql = `
        SELECT id FROM posts 
        WHERE id = ? AND user_id = ? AND status = 1
      `;
      
      const posts = await query(checkSql, [postId, userId]);
      
      if (posts.length === 0) {
        throw new Error('动态不存在或无权限删除');
      }
      
      // 软删除动态
      const deleteSql = `
        UPDATE posts 
        SET status = 0, updated_at = CURRENT_TIMESTAMP 
        WHERE id = ?
      `;
      
      await query(deleteSql, [postId]);
      return true;
    } catch (error) {
      console.error('删除动态失败:', error);
      throw error;
    }
  }

  /**
   * 切换点赞状态
   * @param {number} postId - 动态ID
   * @param {string} userId - 用户ID
   * @returns {Object} 点赞结果
   */
  static async toggleLike(postId, userId) {
    try {
      // 验证动态是否存在
      const post = await Post.getById(postId, userId);
      if (!post) {
        throw new Error('动态不存在');
      }
      
      // 检查是否已点赞
      const checkSql = `
        SELECT id FROM post_likes 
        WHERE post_id = ? AND user_id = ?
      `;
      
      const likes = await query(checkSql, [postId, userId]);
      
      if (likes.length > 0) {
        // 取消点赞
        const deleteSql = `
          DELETE FROM post_likes 
          WHERE post_id = ? AND user_id = ?
        `;
        await query(deleteSql, [postId, userId]);
        
        // 获取更新后的点赞数
        const countSql = `SELECT COUNT(*) as count FROM post_likes WHERE post_id = ?`;
        const countResult = await query(countSql, [postId]);
        
        return {
          isLiked: false,
          likeCount: countResult[0].count
        };
      } else {
        // 添加点赞
        const insertSql = `
          INSERT INTO post_likes (post_id, user_id) 
          VALUES (?, ?)
        `;
        await query(insertSql, [postId, userId]);
        
        // 获取更新后的点赞数
        const countSql = `SELECT COUNT(*) as count FROM post_likes WHERE post_id = ?`;
        const countResult = await query(countSql, [postId]);
        
        return {
          isLiked: true,
          likeCount: countResult[0].count
        };
      }
    } catch (error) {
      console.error('切换点赞状态失败:', error);
      throw error;
    }
  }

  /**
   * 获取动态点赞列表
   * @param {number} postId - 动态ID
   * @param {string} currentUserId - 当前用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 点赞列表和分页信息
   */
  static async getLikes(postId, currentUserId, page = 1, limit = 20) {
    try {
      // 验证动态是否存在
      const post = await Post.getById(postId, currentUserId);
      if (!post) {
        throw new Error('动态不存在');
      }
      
      // 确保参数为整数类型
      page = parseInt(page);
      limit = parseInt(limit);
      
      const offset = (page - 1) * limit;
      
      const sql = `
        SELECT 
          pl.user_id as userId,
          u.nick_name as nickName,
          u.avatar,
          pl.created_at as likedAt
        FROM post_likes pl
        LEFT JOIN users u ON pl.user_id = u.user_id
        WHERE pl.post_id = ?
        ORDER BY pl.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const likes = await query(sql, [postId]);
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM post_likes 
        WHERE post_id = ?
      `;
      
      const countResult = await query(countSql, [postId]);
      const total = countResult[0].total;
      
      return {
        likes,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取点赞列表失败:', error);
      throw error;
    }
  }
}

module.exports = Post;